<template>
  <button type="button" class="code-btn" @click="clickButton()" :disabled="isBtnDisabled">{{ btnText }}</button>
</template>

<script>
export default {
  name: 'VCodeButton',
  props: {
    status: {
      type: Number,
      default: 0
    }
  },
  data () {
    return {
      btnText: this.$t('message.getCode'),
      isBtnDisabled: false,
      totalTime: 60
    }
  },
  watch: {
    // 0:获取验证码
    // 1:发送中
    // 2:倒计时
    status (val) {
      if (val === 0) {
        clearInterval(this.timer)
        this.isBtnDisabled = false
        this.btnText = this.$t('message.getCode')
      } else if (val === 1) {
        this.isBtnDisabled = true
        this.btnText = this.$t('message.sending')
      } else if (val === 2) {
        this.isBtnDisabled = true
        this.btnTimer()
      }
    }
  },
  methods: {
    clickButton () {
      this.$emit('click-button')
    },
    // 按钮文字计时
    btnTimer () {
      clearInterval(this.timer)
      let time = this.totalTime
      this.btnText = this.$t('message.sendAgain') + '(' + time + ')'
      this.timer = setInterval(() => {
        if (time > 0) {
          time--
          this.btnText = this.$t('message.sendAgain') + '(' + time + ')'
        } else {
          clearInterval(this.timer)
          this.isBtnDisabled = false
          this.btnText = this.$t('message.getCode')
        }
      }, 1000)
    }
  },
  destroyed () {
    clearInterval(this.timer)
  }
}
</script>

<style scoped>
.code-btn {
  width: 100%;
  height: 100%;
  border: 0;
  border-radius: 2px;
  background-color: #ff600a;
  color: #fff;
  cursor: pointer;
}

.code-btn:hover {
  background-color: #ff3c00;
}

.code-btn:active {
  background-color: #e83700;
}

.code-btn:disabled {
  background-color: #f0f0f0;
  color: #a5a5a5;
}
</style>